<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>HK.02616 实时K线图</title>
  <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  <style>
    #controls { margin: 10px; }
    #main { width: 100%; height: 600px; }
    .info { margin: 10px; font-size: 14px; }
  </style>
</head>
<body>
  <h2>HK.02616 实时K线图（GetKL 接口）</h2>
  <div id="controls">
    <label>周期: </label>
    <select id="ktype">
      <option value="1m">1 分钟</option>
      <option value="5m">5 分钟</option>
      <option value="15m">15 分钟</option>
      <option value="30m">30 分钟</option>
      <option value="1h">1 小时</option>
      <option value="day">日 K</option>
    </select>
    <button onclick="fetchData()">刷新</button>
  </div>
  <div class="info" id="priceInfo">当前价: — , 最高: — , 最低: —</div>
  <div id="main"></div>

  <script>
    const chartDom = document.getElementById('main');
    const myChart = echarts.init(chartDom);

    let globalData = null;
    let intervalId = null;

    async function fetchData() {
      const ktype = document.getElementById("ktype").value;
      try {
        const resp = await fetch(`http://127.0.0.1:5000/kline?type=${ktype}&num=500`);
        const obj = await resp.json();
        if (obj.error) {
          console.error("获取失败:", obj.error);
          return;
        }

        // 只保留今天的数据（假设 time_key 格式是 'YYYY-MM-DD HH:mm:ss'）
        const today = new Date().toISOString().slice(0, 10); // 'YYYY-MM-DD'
        const filteredIdx = obj.times.map((t, i) => t.startsWith(today) ? i : -1).filter(i => i >= 0);
        const times = filteredIdx.map(i => obj.times[i]);
        const kline = filteredIdx.map(i => obj.kline[i]);
        const volumes = filteredIdx.map(i => obj.volumes[i]);
        const turnovers = filteredIdx.map(i => obj.turnovers[i]);
        const turnover_rates = filteredIdx.map(i => obj.turnover_rates[i]);

        const current_price = kline.length > 0 ? kline[kline.length - 1][1] : null;
        const highest_price = kline.length > 0 ? Math.max(...kline.map(k => k[3])) : null;
        const lowest_price = kline.length > 0 ? Math.min(...kline.map(k => k[2])) : null;

        const data = { times, kline, volumes, turnovers, turnover_rates, current_price, highest_price, lowest_price };
        globalData = data;

        updateInfo(data);
        renderChart(data);

      } catch (err) {
        console.error("请求错误:", err);
      }
    }

    function updateInfo(obj) {
      document.getElementById('priceInfo').innerText =
        `当前价: ${obj.current_price} , 最高: ${obj.highest_price} , 最低: ${obj.lowest_price}`;
    }

    
    function renderChart(obj) {
  const optionOld = myChart.getOption();
  let zoomStart = 0, zoomEnd = 100;
  if (optionOld && optionOld.dataZoom && optionOld.dataZoom.length > 0) {
    zoomStart = optionOld.dataZoom[0].start;
    zoomEnd = optionOld.dataZoom[0].end;
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      formatter: function(params) {
        const idx = params[0].dataIndex;
        return `
          时间: ${obj.times[idx]}<br/>
          开: ${obj.kline[idx][0]} 收: ${obj.kline[idx][1]}<br/>
          高: ${obj.kline[idx][3]} 低: ${obj.kline[idx][2]}<br/>
          成交量: ${obj.volumes[idx]}<br/>
          成交额(万): ${(obj.turnovers[idx]/10000).toFixed(2)}<br/>
          换手率: ${obj.turnover_rates[idx].toFixed(4)}%
        `;
      }
    },
    legend: { data: ['K线', '成交量', '成交额(万)', '换手率'] },
    grid: [
      { left: '10%', right: '10%', top: '10%', height: '55%' }, // 上部 K线
      { left: '10%', right: '10%', top: '70%', height: '20%' }  // 下部成交量/成交额/换手率
    ],
    xAxis: [
      { type: 'category', data: obj.times, scale: true, boundaryGap: true, gridIndex: 0 },
      { type: 'category', data: obj.times, scale: true, boundaryGap: true, gridIndex: 1 }
    ],
    yAxis: [
      { scale: true, name: '价格', gridIndex: 0 },
      { type: 'value', name: '成交量/成交额', gridIndex: 1 },
      { type: 'value', name: '换手率(%)', gridIndex: 1, position: 'right', axisLabel: { formatter: '{value}%' } }
    ],
    dataZoom: [
      { type: 'inside', xAxisIndex: [0, 1], start: zoomStart, end: zoomEnd },
      { type: 'slider', xAxisIndex: [0, 1], start: zoomStart, end: zoomEnd }
    ],
    axisPointer: {
      link: [{ xAxisIndex: [0, 1] }],  // 上下 grid 横坐标联动
      label: { backgroundColor: '#777' }
    },
    series: [
      {
        name: 'K线',
        type: 'candlestick',
        data: obj.kline,
        xAxisIndex: 0,
        yAxisIndex: 0,
        itemStyle: { color: '#00A650', color0: '#FF4D4F', borderColor: '#00A650', borderColor0: '#FF4D4F' }
      },
      {
        name: '成交量',
        type: 'bar',
        data: obj.volumes,
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: { color: '#888888' }
      },
      {
        name: '成交额(万)',
        type: 'bar',
        data: obj.turnovers.map(v => v / 10000),
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: { color: '#4CAF50', opacity: 0.5 }
      },
      {
        name: '换手率',
        type: 'line',
        data: obj.turnover_rates,
        xAxisIndex: 1,
        yAxisIndex: 2,
        smooth: true,
        lineStyle: { color: '#FF4081' }
      }
    ]
  };

  myChart.setOption(option, true); // 保留缩放/拖动位置
}


    // 页面加载时自动 fetch
    fetchData();

    // 实时刷新，每 5 秒更新一次
    if (intervalId) clearInterval(intervalId);
    intervalId = setInterval(fetchData, 5000);
  </script>
</body>
</html>
